<template>
  <div class="group-analysis">
    <div class="analy-header">
      <div
        :class="active == item.id ? 'activeTag' : 'tag'"
        v-for="item in listTab"
        :key="item.id"
        @click="selectTag(item)"
        >{{ item.name }}</div
      >
    </div>
    <!-- 会话摘要分析 -->
    <div class="analy-content" v-if="active == 0">
      <!-- 暂无分析记录 -->
      <div v-if="!analysisData" class="no-analy">
        <div class="no-analy-title mb-20">暂无分析记录,点击下方按钮开始分析</div>
        <el-image :src="IMGURL" style="margin-bottom: 250px"></el-image>
        <el-button type="warning" @click="startAnaly">开始分析</el-button>
      </div>
      <!-- 正在分析中... -->
      <div v-if="analysisData?.jobStatus == 0" class="now-analy">
        <div class="title mb-5">聊天记录正在分析中...</div>
        <div class="title">提交时间:{{ formatDate(analysisData.createTime) }}</div>
        <div v-loading="true" style="height: 566px; width: 100%; background-color: #f6f6f7"></div>
        <el-button type="warning" @click="refreshSummary">刷新</el-button>
      </div>
      <!-- 分析完成 -->
      <div v-if="analysisData?.jobStatus == 1" class="res-analy">
        <div class="title mb-5">分析完成</div>
        <div class="small-title mb-5">为保证分析效率,最大分析量为最近100条文本消息</div>
        <div class="boxs">
          <div class="contents" v-html="textContent"></div>
        </div>
        <el-button type="warning" @click="startAnaly">重新分析</el-button>
      </div>
    </div>

    <!-- 标签分析 -->
    <div class="analy-content" v-if="active == 1">
      <!-- 暂无分析记录 -->
      <div v-if="!tagData" class="no-analy">
        <div class="no-analy-title mb-20">暂无分析记录,点击下方按钮开始分析</div>
        <el-image :src="TagImg" style="margin-bottom: 250px"></el-image>
        <el-button type="warning" @click="startTag">开始分析</el-button>
      </div>
      <!-- 正在分析中 -->
      <div v-if="tagData?.jobStatus == 0" class="now-analy">
        <div class="title mb-5">客户标签正在分析中...</div>
        <div class="title">提交时间:{{ formatDate(tagData.createTime) }}</div>
        <div v-loading="true" style="height: 566px; width: 100%; background-color: #f6f6f7"></div>
        <el-button type="warning" @click="refreshTag">刷新</el-button>
      </div>
      <!-- 分析完成 -->
      <div v-if="tagData?.jobStatus == 1" class="res-analy">
        <div class="title mb-5">分析完成</div>
        <div class="boxs">
          <div class="contents">
            <el-tag type="success" v-for="item in tagData?.result" :key="item.group_id">{{
              item.tag_name
            }}</el-tag>
            <el-empty description="没有数据" v-if="tagData?.result.length"></el-empty>
          </div>
        </div>
        <el-button type="warning" @click="startTag">重新分析</el-button>
      </div>
    </div>

    <!-- 情感分析 -->
    <div class="analy-content" v-if="active == 2">
      <!-- 暂无分析记录 -->
      <div v-if="!sentimentData" class="no-analy">
        <div class="no-analy-title mb-20">暂无分析记录,点击下方按钮开始分析</div>
        <el-image :src="TentimentImg" style="margin-bottom: 250px"></el-image>
        <el-button type="warning" @click="startSentiment">开始分析</el-button>
      </div>
      <!-- 正在分析中 -->
      <div v-if="sentimentData?.jobStatus == 0" class="now-analy">
        <div class="title mb-5">情感分析正在分析中...</div>
        <div class="title">提交时间:{{ formatDate(sentimentData.createTime) }}</div>
        <div v-loading="true" style="height: 566px; width: 100%; background-color: #f6f6f7"></div>
        <el-button type="warning" @click="refreshSentiment">刷新</el-button>
      </div>
      <!-- 分析完成 -->
      <div v-if="sentimentData?.jobStatus == 1" class="res-analy">
        <div class="title mb-5">分析完成</div>
        <div class="boxs">
          <div class="contents">
            <div class="positive">
              <span class="icon"></span>
              <span class="contents">正面情绪:{{ emotionAnalysis.positiveNum }}</span></div
            >
            <div class="emotionless"
              ><span class="icon"></span
              ><span class="contents">中性情绪:{{ emotionAnalysis.emotionlessNum }}</span></div
            >
            <div class="negative"
              ><span class="icon"></span
              ><span class="contents">负面情绪:{{ emotionAnalysis.negativeNum }}</span></div
            >
          </div>
        </div>
        <el-button type="warning" @click="startSentiment">重新分析</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  getSummaryTask,
  createSummaryTask,
  createTagTask,
  getTagTask,
  createSentimenTask,
  getSentimenTask
} from '@/api/wecom/sessionAudit/index'
import { formatDate } from '@/utils/formatTime'
import IMGURL from '@/assets/imgs/analy.png'
import TagImg from '@/assets/imgs/tag.jpg'
import TentimentImg from '@/assets/imgs/sentiment.jpg'
import log from '@/utils/log'

const listTab = [
  {
    name: '会话摘要分析',
    id: 0
  },
  {
    name: '客户标签分析',
    id: 1
  },
  {
    name: '情感分析',
    id: 2
  }
]

const emit = defineEmits(['setMsgList'])

const emotionAnalysis = ref({
  emotionlessNum: 0, //无情感
  positiveNum: 0, //证明
  negativeNum: 0 //负面
})
const analysisData = ref(null)
const tagData = ref(null)
const sentimentData = ref(null)
const chatId = ref(null)
const props = defineProps({
  wecomItem: Object
})
// 刷新三次
const timer = ref(null)
const num = ref(0)

const timerTag = ref(null)
const numTag = ref(0)

const timerSentiment = ref(null)
const numSentiment = ref(0)
// tab
const active = ref(0)
const selectTag = (item) => {
  active.value = item.id
  if (item.id == 0) {
    getGroupSummary()
  } else if (item.id == 1) {
    getGroupTag()
  } else {
    getSentiment()
  }
}
//获取客户群会话摘要分析
const getGroupSummary = async () => {
  analysisData.value = await getSummaryTask({ chatId: chatId.value })
  log.info('会话摘要状态', analysisData.value?.jobStatus)
  if (analysisData.value?.jobStatus == 1 && timer.value) {
    clearInterval(timer.value)
    num.value = 0
  }
}

// 文本
const textContent = computed(() => {
  if (analysisData.value?.result) {
    return analysisData.value?.result
      .split('\n') // 按换行符分割
      .map((line) => `&nbsp;&nbsp;${line}`) // 每行前添加两个空格
      .join('<br/>') // 用 <br/> 连接每行
  }
})

// 重新刷新
const refreshSummary = async () => {
  await getGroupSummary()
  ElMessage.success('刷新会话摘要分析成功!')
}
//重新刷新标签
const refreshTag = async () => {
  await getGroupTag()
  ElMessage.success('刷新客户标签分析成功!')
}
watch(
  () => props.wecomItem,
  (val) => {
    if (val) chatId.value = val.chatId || val.weUserId
    getGroupSummary()
  },
  { immediate: true, deep: true }
)

// 开始分析
const startAnaly = async () => {
  const data = await createSummaryTask({ chatId: chatId.value })
  if (data) {
    ElMessage.success('创建会话摘要分析成功,正在分析中...')
    refreshAnaly()
  }
}
// 刷新会话
const refreshAnaly = () => {
  if (timer.value) clearInterval(timer.value)
  timer.value = setInterval(() => {
    if (num.value == 3) {
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
        num.value = 0
      }
    } else {
      num.value++
      getGroupSummary()
    }
  }, 3e3)
}

// 获取客户标签任务
const getGroupTag = async () => {
  let data = await getTagTask({ chatId: chatId.value })
  if (data?.result) data.result = JSON.parse(data.result)
  tagData.value = data
  if (tagData.value?.jobStatus == 1 && timerTag.value) {
    clearInterval(timerTag.value)
    numTag.value = 0
  }
  log.error('tagData.value', JSON.stringify(tagData.value))
}
// 刷新标签
const refreshTags = () => {
  if (timerTag.value) clearInterval(timerTag.value)
  timerTag.value = setInterval(() => {
    if (numTag.value == 3) {
      if (timerTag.value) {
        clearInterval(timerTag.value)
        timerTag.value = null
        numTag.value = 0
      }
    } else {
      numTag.value++
      getGroupTag()
    }
  }, 3e3)
}
// 创建客户标签任务
const startTag = async () => {
  let data = await createTagTask({ chatId: chatId.value })
  if (data) {
    ElMessage.success('创建客户标签分析成功,正在分析中...')
    refreshTags()
  }
}

// 获取情感任务
const getSentiment = async () => {
  const data = await getSentimenTask({ chatId: chatId.value })
  if (data?.result) {
    data.result = JSON.parse(data.result)
    emit('setMsgList', data.result)
    emotionAnalysis.value.emotionlessNum = data.result.filter(
      (item) => item.sentiment_result == 0
    ).length //无情感
    emotionAnalysis.value.positiveNum = data.result.filter(
      (item) => item.sentiment_result == 1
    ).length //正面
    emotionAnalysis.value.negativeNum = data.result.filter(
      (item) => item.sentiment_result == 2
    ).length //负面
  }
  sentimentData.value = data
  if (sentimentData.value?.jobStatus == 1 && timerSentiment.value) {
    clearInterval(timerSentiment.value)
    numSentiment.value = 0
  }
}
// 刷新情感标签
const refreshSentiment = async () => {
  await getSentiment()
  ElMessage.success('刷新情感分析成功!')
}
// 刷新情感
const refreshSentiments = () => {
  if (timerSentiment.value) clearInterval(timerSentiment.value)
  timerSentiment.value = setInterval(() => {
    if (numSentiment.value == 3) {
      if (timerSentiment.value) {
        clearInterval(timerSentiment.value)
        timerSentiment.value = null
        numSentiment.value = 0
      }
    } else {
      numSentiment.value++
      getSentiment()
    }
  }, 3e3)
}
//创建情感任务
const startSentiment = async () => {
  let data = await createSentimenTask({ chatId: chatId.value })
  if (data) {
    ElMessage.success('创建情感分析成功,正在分析中...')
    refreshSentiments()
  }
}
</script>

<style scoped lang="scss">
.group-analysis {
  height: 72px;
  border-bottom: 1px solid #e0e1e2;
  .analy-header {
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .tag {
      cursor: pointer;
      font-size: 14px;
      padding: 10px;
      border-radius: 4px;
      color: #6d7176;
    }
    .activeTag {
      background-color: #eaeaec;
      color: #000000;
      cursor: pointer;
      font-size: 14px;
      padding: 10px;
      border-radius: 4px;
    }
  }
  .analy-content {
    height: calc(100% - 73px);
    .now-analy {
      padding: 100px 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 14px;
        color: #959291;
      }
    }
    .res-analy {
      padding: 40px 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 14px;
        color: #505f79;
      }
      .small-title {
        font-size: 14px;
        color: #e6a23c;
      }
      .boxs {
        height: 566px;
        margin-bottom: 20px;
        overflow-y: auto;
        .contents {
          font-size: 14px;
          line-height: 28px;
          color: #3e4248;
          .positive {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            font-size: 18px;
            margin-bottom: 10px;
            .icon {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-right: 10px;
              background-color: #f36a62;
            }
          }
          .negative {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            font-size: 18px;
            margin-bottom: 10px;
            .icon {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-right: 10px;
              background-color: #d4d5d7;
            }
          }
          .emotionless {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            font-size: 18px;
            align-items: center;
            margin-bottom: 10px;
            .icon {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-right: 10px;
              background-color: #0052cc;
            }
          }
        }
        &::-webkit-scrollbar {
          width: 2px;
        }
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
        }
        &::-webkit-scrollbar-thumb {
          background: #d8d8d8;
        }
        &::-webkit-scrollbar-thumb:hover {
          background: #d8d8d8;
        }
        &::-webkit-scrollbar-thumb:horizontal:start {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        &::-webkit-scrollbar-thumb:horizontal:end {
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
      }
    }
    .no-analy {
      padding: 40px 10px 100px 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 14px;
        color: #959291;
      }
      .no-analy-title {
        font-size: 16px;
        color: #000000;
        font-weight: bold;
      }
    }
  }
}
::v-deep .el-loading-mask {
  background-color: #f6f6f7;
}
</style>
